//
//  RankingView.m
//  Dispatch
//
//  Created by hyeyeon on 14. 1. 14..
//  Copyright (c) 2014년 hyeyeon. All rights reserved.
//

#import "RankingView.h"

#define UD_MALE_SELECT  @"UD_MALE_SELECT"

@implementation RankingView
@synthesize responseData, imageURL, maleItemArray, femaleItemArray;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
        
        myRect = frame;
        appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        self.responseData = [NSMutableData data];
        maleItemArray = [[NSMutableArray alloc] init];
        femaleItemArray = [[NSMutableArray alloc] init];
        
        
        [self makeObject];
        
        
        topMoveButton = [[UIButton alloc] initWithFrame:CGRectMake(mySize.width-10-35, frame.size.height-44-35-10, 35, 35)];
        [topMoveButton setImage:[UIImage imageNamed:@"btn_top"] forState:UIControlStateNormal];
        [topMoveButton addTarget:self action:@selector(topMoveButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:topMoveButton];
        
        self.backgroundColor = ColorFromRGB(0x4d4d57);

    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

#pragma mamrk - 생성
-(void)makeObject{
    
    manButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 150, 29)];
    [manButton setBackgroundImage:[UIImage imageNamed:@"bar_man"] forState:UIControlStateNormal];
    [manButton setBackgroundImage:[UIImage imageNamed:@"bar_man_on"] forState:UIControlStateSelected];
    [manButton addTarget:self action:@selector(manButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:manButton];
    
    manLabel = [[UILabel alloc] initWithFrame:CGRectMake(77, 0, manButton.frame.size.width-77, manButton.frame.size.height)];
    manLabel.backgroundColor = [UIColor clearColor];
    manLabel.text = NSLocalizedString(@"man", @"");
    manLabel.textColor = ColorFromRGB(0x49a1d9);
    manLabel.font = [UIFont systemFontOfSize:14];
    [manButton addSubview:manLabel];
    
    womanButton = [[UIButton alloc] initWithFrame:CGRectMake(manButton.frame.origin.x+manButton.frame.size.width,
                                                             manButton.frame.origin.y,
                                                             manButton.frame.size.width,
                                                             manButton.frame.size.height)];
    [womanButton setBackgroundImage:[UIImage imageNamed:@"bar_woman"] forState:UIControlStateNormal];
    [womanButton setBackgroundImage:[UIImage imageNamed:@"bar_woman_on"] forState:UIControlStateSelected];
    [womanButton addTarget:self action:@selector(womanButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:womanButton];
    
    womanLabel = [[UILabel alloc] initWithFrame:manLabel.frame];
    womanLabel.backgroundColor = [UIColor clearColor];
    womanLabel.text = NSLocalizedString(@"woman", @"");
    womanLabel.textColor = ColorFromRGB(0x49a1d9);
    womanLabel.font = [UIFont systemFontOfSize:14];
    [womanButton addSubview:womanLabel];
    
    
    //table
    mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, manButton.frame.origin.y+manButton.frame.size.height+10, mySize.width, myRect.size.height-10-manButton.frame.size.height-10)];
    mTableView.delegate = self;
    mTableView.dataSource = self;
    mTableView.backgroundColor = ColorFromRGB(0x4d4d57);
    mTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self addSubview:mTableView];
    
    _refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - mTableView.bounds.size.height, mTableView.frame.size.width, mTableView.bounds.size.height)];
    _refreshHeaderView.delegate = self;
    [mTableView addSubview:_refreshHeaderView];
    [_refreshHeaderView refreshLastUpdatedDate];
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:UD_MALE_SELECT]) {
        [self manButtonAction:manButton];
    }else{
        [self womanButtonAction:womanButton];
    }
    

    
    
}

#pragma mark - 로딩


-(void)makeActivityIndicatorView{
    activieiBGView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mTableView.frame.size.width, 50)];
    activieiBGView.backgroundColor = ColorFromRGB(0x4d4d57);
    
    activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    activityView.center = CGPointMake(mTableView.frame.size.width*0.5f, 25);
    [activieiBGView addSubview:activityView];
    
}

#pragma mark - 위로가기
-(void)topMoveButtonAction:(id)sender{
    [mTableView setContentOffset:CGPointMake(0, 0) animated:YES];
}

#pragma mark - 다음페이지

-(void)loadNextPage{
    if ([[NSUserDefaults standardUserDefaults] boolForKey:UD_MALE_SELECT]) {
        
        if (isEndM) {
            
            [self requestStarsPage:currentPageM andMale:YES];
            
        }else{
            
            [appDelegate alertViewWithMessage:NSLocalizedString(@"Last page", @"") andTimeInterval:2.0f];
        }
    }else{
        if (isEndF) {
            
            [self requestStarsPage:currentPageF andMale:NO];
        }else{
            
            [appDelegate alertViewWithMessage:NSLocalizedString(@"Last page", @"") andTimeInterval:2.0f];
        }
    }
}

#pragma mark - 상세보기

-(void)listLeftButtonClick:(id)sender{
    
    UIButton *button = (UIButton*)sender;
    [self appearStarListToID:button.tag];

}

-(void)listRightButtonClick:(id)sender{
    
    UIButton *button = (UIButton*)sender;
    [self appearStarListToID:button.tag];
}

-(void)appearStarListToID:(NSInteger)index{
    
    ViewController *viewController = (ViewController*)self.window.rootViewController;
    NSString *starID = @"";
    if ([[NSUserDefaults standardUserDefaults] boolForKey:UD_MALE_SELECT]) {
        //남
        starID = [[self.maleItemArray objectAtIndex:index] objectForKey:@"star_id"];
    }else{
        //여
        starID = [[self.femaleItemArray objectAtIndex:index] objectForKey:@"star_id"];
    }
    
    [viewController appearStarListToID:starID];
}

#pragma mark - 남/녀 선택
-(void)manButtonAction:(id)sender{
    
    [appDelegate analyticsCategory:ANA_CAT_PAGE Action:ANA_ACT_STAR Label:ANA_LAB_Star_Male];
    
    manButton.selected = YES;
    manLabel.textColor = ColorFromRGB(0xffffff);
    
    womanButton.selected = NO;
    womanLabel.textColor = ColorFromRGB(0x49a1d9);
    
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:UD_MALE_SELECT];
    
    if (self.maleItemArray.count <= 0) {
        
        [self requestStarsPage:1 andMale:YES];
    }else{
        
        [mTableView reloadData];
    }
    
}

-(void)womanButtonAction:(id)sender{
    
    [appDelegate analyticsCategory:ANA_CAT_PAGE Action:ANA_ACT_STAR Label:ANA_LAB_Star_Female];
    
    womanButton.selected = YES;
    womanLabel.textColor = ColorFromRGB(0xffffff);
    
    manButton.selected = NO;
    manLabel.textColor = ColorFromRGB(0x49a1d9);
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:UD_MALE_SELECT];
    
    if (self.femaleItemArray.count <= 0) {
        [self requestStarsPage:1 andMale:NO];
    }else{
        [mTableView reloadData];
    }
    
}
#pragma mark - 스크롤잡기

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	_reloading = YES;
	
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:mTableView];
	
}

#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}


#pragma mark - 네트워크
-(void)requestStarsPage:(int)index andMale:(BOOL)yn{
    
    if (yn) {
        currentPageM = index;
    }else{
        currentPageF = index;
    }
//    NSLog(@"currentPageM : %d | currentPageF : %d",currentPageM, currentPageF);
    

    [activityView startAnimating];
    manButton.enabled = womanButton.enabled = NO;   //네트워크 부를동안은 막아버림
    NSString *dataStr = [NSString stringWithFormat:@"page=%d&lang=%@&gender=%d&pagesize=100",index,appDelegate.currentLanguage,yn?1:2];
    dataStr = [appDelegate encryptDataURLString:dataStr];
    NSString *url = [NSString stringWithFormat:@"%@?p=%@",URL_STARS,dataStr];
    [self requestURL:url];
}

-(void)requestURL:(NSString*)url{
    
    [self performSelectorOnMainThread:@selector(startRequestWithURL:) withObject:url waitUntilDone:NO];
}

-(void)startRequestWithURL:(NSString*)url{
    @autoreleasepool {
        
        duringNetwork = YES;
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        if (url) {
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
            [request setHTTPMethod:@"POST"];
            
            NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
            
            if(connection){
                NSLog(@"량킹리스트 네트워크 요청 : %@",url);
            }
            
            [mTableView reloadData];
            
        }
    }
}


#pragma mark delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    [self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connectio{
    
    manButton.enabled = womanButton.enabled = YES;
    duringNetwork = NO;
    
    NSError *myError = nil;
    NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
    
    self.imageURL = ([appDelegate checkObject:[resultDictionary objectForKey:@"imgurl"]]) ? [resultDictionary objectForKey:@"imgurl"] : nil;
    
    
    if ([resultDictionary objectForKey:@"return_code"]) {
        if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0){
            
            resultDictionary = [resultDictionary objectForKey:@"data"];
            NSLog(@"랭킹리스트 : %@",resultDictionary);
            
            if ([[NSUserDefaults standardUserDefaults] boolForKey:UD_MALE_SELECT]) {
                
                if (currentPageM <= 1) {
                    [self.maleItemArray removeAllObjects];
                }
                
                currentPageM++;

                isEndM = ([appDelegate checkObject:[resultDictionary objectForKey:@"isend"]]) ? [[resultDictionary objectForKey:@"isend"] boolValue] : NO;
                NSArray *items_m = ([appDelegate checkObject:[resultDictionary objectForKey:@"items"]]) ? [resultDictionary objectForKey:@"items"] : nil;
                if (items_m) {
                    [self.maleItemArray addObjectsFromArray:items_m];
                }
                
                NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
                [notification postNotificationName:ITEM_LIST_LOAD object:self.maleItemArray];
                
            }else{
                
                if (currentPageF <= 1) {
                    [self.femaleItemArray removeAllObjects];
                }
                
                currentPageF++;
                isEndF = ([appDelegate checkObject:[resultDictionary objectForKey:@"isend"]]) ? [[resultDictionary objectForKey:@"isend"] boolValue] : NO;
                NSArray *items_f = ([appDelegate checkObject:[resultDictionary objectForKey:@"items"]]) ? [resultDictionary objectForKey:@"items"] : nil;
                
                if (items_f) {
                    [self.femaleItemArray addObjectsFromArray:items_f];
                }
                
                NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
                [notification postNotificationName:ITEM_LIST_LOAD object:self.femaleItemArray];
            }
            
            [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0.5f];
            [mTableView reloadData];
            
        }
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    duringNetwork = NO;
    manButton.enabled = womanButton.enabled = YES;
    NSLog(@"랭킹리스트 네트워크 요청 실패 : %@",error);
}

#pragma mark - UITableView Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        
        NSInteger numberOfRows = 0;
        if ([[NSUserDefaults standardUserDefaults] boolForKey:UD_MALE_SELECT]) {
            //남
            numberOfRows = ([self.maleItemArray count]%2 == 0) ? (int)([self.maleItemArray count]/2) : (int)([self.maleItemArray count]/2)+1;
        }else{
            //여
            numberOfRows = ([self.femaleItemArray count]%2 == 0) ? (int)([self.femaleItemArray count]/2) : (int)([self.femaleItemArray count]/2)+1;
        }
        
        return numberOfRows;
    }else{
        return 1;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 146;
    }else{
        return 50;
    }

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        static NSString *CellIdentifier = @"RankingCell";
        ListCell *cell = (ListCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[ListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.delegate = self;
            cell.backgroundColor = [UIColor clearColor];
        }
        
        NSString *first, *second;
        
        NSArray *itemArray = [[NSUserDefaults standardUserDefaults] boolForKey:UD_MALE_SELECT] ? self.maleItemArray : self.femaleItemArray;
        
        if ((indexPath.row*2) < [itemArray count]) {
            
            //재사용시 기존 이미지 가림
            if (!cell.leftImage.image || cell.leftImage.tag != indexPath.row) {
                cell.leftImage.image = nil;
                [cell cellLeftIconImage:nil];
            }
            
            first = [[itemArray objectAtIndex:indexPath.row*2] objectForKey:@"name"];
            cell.leftImage.tag = indexPath.row;
            cell.leftButton.tag = indexPath.row*2;
            cell.leftNumberLabel.text = [[itemArray objectAtIndex:indexPath.row*2] objectForKey:@"ranking"];
            [cell.leftButton addTarget:self action:@selector(listLeftButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            
            
            [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:[[itemArray objectAtIndex:indexPath.row*2] objectForKey:@"thumb_url"] imageBlock:^(UIImage *image) {
                
                if (cell.leftImage.tag == indexPath.row) {
                    
                    cell.leftImage.image = image;
                    [appDelegate effectFaceoutTargetView:cell.leftImage];
                }
            } errorBlock:^{
                
                if (cell.leftImage.tag == indexPath.row) {
                    
                    cell.leftImage.image = nil;
                }
            }];
            
            
            //리본아이콘
            NSString *icon = [[itemArray objectAtIndex:indexPath.row*2] objectForKey:@"icon"];
            if ([appDelegate checkObject:icon]) {
                NSString *imgurl = [appDelegate.iconDictionary objectForKey:icon];
                cell.leftIcon.tag = indexPath.row;
                
                
                [appDelegate loadAsyncImageFromURLString:imgurl imageBlock:^(UIImage *image) {
                    
                    if (cell.leftIcon.tag == indexPath.row) {
                        
                        [cell cellLeftIconImage:image];
                    }
                } errorBlock:^{
                    
                    [cell cellLeftIconImage:nil];
                }];
            }
        }
        if ((indexPath.row*2)+1 < [itemArray count]) {
            
            //재사용시 기존 이미지 가림
            if (!cell.rightImage.image || cell.rightImage.tag != indexPath.row) {
                cell.rightImage.image = nil;
                [cell cellRightIconImage:nil];
            }
            
            second = [[itemArray objectAtIndex:(indexPath.row*2)+1] objectForKey:@"name"];
            cell.rightImage.tag = indexPath.row;
            cell.rightButton.tag = (indexPath.row*2)+1;
            cell.rightNumberLabel.text = [[itemArray objectAtIndex:(indexPath.row*2)+1] objectForKey:@"ranking"];
            [cell.rightButton addTarget:self action:@selector(listRightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            
            
            [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:[[itemArray objectAtIndex:(indexPath.row*2)+1] objectForKey:@"thumb_url"] imageBlock:^(UIImage *image) {
                
                if (cell.rightImage.tag == indexPath.row) {
                    
                    cell.rightImage.image = image;
                    [appDelegate effectFaceoutTargetView:cell.rightImage];
                }
            } errorBlock:^{
                
                if (cell.rightImage.tag == indexPath.row) {
                    
                    cell.rightImage.image = nil;
                }
            }];
            
            //리본아이콘
            NSString *icon = [[itemArray objectAtIndex:(indexPath.row*2)+1] objectForKey:@"icon"];
            if ([appDelegate checkObject:icon]) {
                NSString *imgurl = [appDelegate.iconDictionary objectForKey:icon];
                cell.rightIcon.tag = indexPath.row;
                
                [appDelegate loadAsyncImageFromURLString:imgurl imageBlock:^(UIImage *image) {
                    
                    if (cell.leftIcon.tag == indexPath.row) {
                        
                        [cell cellRightIconImage:image];
                    }
                } errorBlock:^{
                    
                    [cell cellRightIconImage:nil];
                }];
            }
        }
        
        [cell cellOfIssueWithHotList:nil andFirstTitle:first andSecondTitle:second];
        cell.leftTitle.textAlignment = cell.rightTitle.textAlignment = NSTextAlignmentCenter;
        
        return cell;
    }else{
        
        static NSString *CellIdentifier = @"UITableViewCell";
        UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            [self makeActivityIndicatorView];
            [cell.contentView addSubview:activieiBGView];
        }
        
//        [activityView startAnimating];
        
        return cell;
    }
}


#pragma mark - UIScrollView Delegate
//다음페이지 이동
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (!duringNetwork) {
        
        if (([scrollView contentOffset].y+scrollView.frame.size.height) == [scrollView contentSize].height) {
            //다음페이지로 이동
            [self loadNextPage];
        }
    }
    
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    [viewController sdkHidden:NO];
    topMoveButton.hidden = NO;
}

//업데이트
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    if (!duringNetwork) {
        if (scrollView.contentOffset.y < -50) {
            //가장첫페이지
            [self requestStarsPage:1 andMale:[[NSUserDefaults standardUserDefaults] boolForKey:UD_MALE_SELECT]];
            
        }
    }
    
    if (!decelerate) {
        
        ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
        [viewController sdkHidden:NO];
        topMoveButton.hidden = NO;
    }
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    [viewController sdkHidden:YES];
    topMoveButton.hidden = YES;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

@end
